//
//  LocationReporterManager.swift
//  BTE
//  埋点
//  Created by Mike Zhang on 2025/8/5.
//


import CoreLocation
import UIKit

/// 表示一个位置上报事件的数据模型
struct TrackingEvent {
    var step: String // 步骤
    var startTimestamp: String // 开始时间（秒级时间戳）
    var endTimestamp: String // 结束时间（秒级时间戳）
    var orderId: String?
}



/// 位置获取与上报管理器
class BTELocationReporterManager: NSObject, CLLocationManagerDelegate {
    
    static let shared = BTELocationReporterManager()
    
    let server = BTEUploadToolNetServer()
    
    private lazy var locationManager: CLLocationManager = {
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.delegate = self
        return manager
    }()
    
    private var locationCompletion: ((String, String) -> Void)?
    
    private var timeoutTask: DispatchWorkItem?

    /// 获取当前定位信息并上报到 STSBMDTool
    func reportLocation(for event: TrackingEvent) {
        getCurrentLocation {[weak self] latitude, longitude in
            var data: [String: String] = [:]
            data["comortgagee"] = event.step
            data["skeldock"] = event.startTimestamp
            data["glomerella"] = event.endTimestamp
            
            if let orderId = event.orderId {
                data["amtrak"] = orderId
            }
            
            // 处理经纬度（精确到小数点后 6 位）
            data["noncomplacent"] = latitude.isEmpty ? "" : "\(floor(Double(latitude)! * 1_000_000) / 1_000_000)"
            data["reposes"] = longitude.isEmpty ? "" : "\(floor(Double(longitude)! * 1_000_000) / 1_000_000)"
            
            data["copelidine"] = "2" // 1 = Android, 2 = iOS
            data["unpleasurable"] = BTEDeviceIdentifierManager.shared.vendorID()
            data["unreprievably"] = BTEDeviceIdentifierManager.shared.advertisingID()
           
            self?.server.impersonative(data: data) { result in
                switch result {
                case .success(let success):
                    print("上传卖点成功")
                    break
                case .failure(let failure):
                    print("上传卖点失败")
                    break
                }
            }
        }
    }

    /// 获取当前定位信息，回调返回经纬度字符串
    func getCurrentLocation(completion: @escaping (String, String) -> Void) {
        self.locationCompletion = completion
        handleAuthorizationStatus(locationManager.authorizationStatus)
    }

    /// 处理定位权限状态
    private func handleAuthorizationStatus(_ status: CLAuthorizationStatus) {
        switch status {
        case .authorizedAlways, .authorizedWhenInUse:
            // 设置 30 秒超时任务
            timeoutTask = DispatchWorkItem { [weak self] in
                DispatchQueue.main.async {
                    self?.locationCompletion?("", "")
                    self?.cleanup()
                }
            }
            DispatchQueue.global().asyncAfter(deadline: .now() + 30, execute: timeoutTask!)
            locationManager.startUpdatingLocation()
            
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            
        default:
            DispatchQueue.main.async {
                self.locationCompletion?("", "")
                self.cleanup()
            }
        }
    }

    /// 清理任务和状态
    private func cleanup() {
        locationManager.stopUpdatingLocation()
        timeoutTask?.cancel()
        locationCompletion = nil
        timeoutTask = nil
    }
    
    
    // MARK: - CLLocationManagerDelegate
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        handleAuthorizationStatus(manager.authorizationStatus)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        DispatchQueue.main.async {
            let latitude = "\(location.coordinate.latitude)"
            let longitude = "\(location.coordinate.longitude)"
            self.locationCompletion?(latitude, longitude)
            self.cleanup()
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        DispatchQueue.main.async { [weak self] in
            self?.locationCompletion?("", "")
            self?.cleanup()
        }
    }
}

